package com.heitian.ssm.utils;



import com.heitian.ssm.controller.UserController;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: mishuai
 * Date: 18-04-08
 * Time: 下午10:48
 * Des:
 */
public class CookieUtil {
    private final static Logger logger = Logger.getLogger(CookieUtil.class);


    public static Map<String, String> getCookies(HttpServletRequest request) {
        Map<String, String> cookieMaps = null;
        if ((cookieMaps = (Map<String, String>) request.getAttribute("w_cookie")) != null) {
            return cookieMaps;
        }
        cookieMaps = new HashMap<String, String>();
        String cookies = request.getHeader("Cookie");
        try {
            if (cookies != null) {
                String[] strings = cookies.split("\\;");
                for (String s : strings) {
                    s = s.trim();
                    int i = s.indexOf("=");
                    String k = s.substring(0, i);
                    String v = s.substring(i + 1, s.length());
                    cookieMaps.put(k.trim(), v.trim());
                }
            }
        } catch (Exception e) {
            logger.info("analysis cookie fail，cookie={},msg:{}");
        }
        request.setAttribute("w_cookie", cookieMaps);
        return cookieMaps;
    }

    public static String getCookie(HttpServletRequest request, String key) {
        Map<String, String> cookies = getCookies(request);
        return cookies.get(key);
    }
//    public static void createCookie(HttpServletResponse response, String key, String value, String expires) {
//        StringBuilder stringBuilder = new StringBuilder(key);
//        stringBuilder.append("=").append(value).append(";");
//        if (expires != null) {
//            stringBuilder.append("Expires=").append(expires).append(";");
//        }
//        stringBuilder.append("path=/;");
//        stringBuilder.append("domain=.")
//                .append(DomainUtil.getDomain())
//                .append(";HttpOnly ");
//
//        response.addHeader("Set-Cookie", stringBuilder.toString());
//    }
//

}



